<template>
  <div class="gspRov">
    <h2>Login to your account</h2>
    <form @submit.prevent="handleSubmit">
      <ul v-if="errors && errors.length > 0" class="errors">
        <li v-for="(error, index) in errors" :key="index">
          {{ error.field }} {{ error.message }}
        </li>
      </ul>
      <input type="email" placeholder="email" v-model="form.email" />
      <input type="password" placeholder="password" v-model="form.password" />
      <div class="action input-group">
        <span class="pointer">Signup instead</span>
        <button :disabled="isLoading">Login</button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { login } from "@/api/user";
import { useRoute, useRouter } from "vue-router";
import type { IError } from "../index";
import useUserStore from "@/store/user";

const router = useRouter();
const route = useRoute();
const useStore = useUserStore();
const form = reactive({
  email: "",
  password: "",
});
const errors = ref<IError>();
const isLoading = ref(false);

async function handleSubmit() {
  try {
    isLoading.value = true;
    errors.value = [];
    const { data } = await login(form);
    useStore.setUserInfo(data);
    const redirect = (route.query.redirect as string) || "/";
    router.push(redirect);
  } catch (err) {
    if ((err as any).response.status === 422) {
      errors.value = (err as any).response.data.detail as IError;
    }
  } finally {
    isLoading.value = false;
  }
}
</script>
